using System.Net;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Admin.NET.Application.Entity.Business;
using Admin.NET.Application.Service.Platform.Dto;
using Admin.NET.Application.Util;
using Admin.NET.Core;
using Furion;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Admin.NET.Application.Service.Platform;

/// <summary>
/// 平台配置
/// </summary>
public class PlatformConfigService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<PlatformConfig> _rep;

	public PlatformConfigService(SqlSugarRepository<PlatformConfig> rep)
	{
		_rep = rep;
	}

	[HttpGet("/platform/getPlatformConfig")]
	[NonUnify]
	[AllowAnonymous]
	public async Task<dynamic> GetPlatformConfig()
	{
		string host = App.HttpContext.Request.Host.Host;
		return await _rep.GetFirstAsync((PlatformConfig u) => u.WebUrl == host);
	}

	[HttpPost("/platform/addPlatformConfig")]
	public async Task AddPlatformConfig(PlatformInput input)
	{
		PlatformConfig entity = input.Adapt<PlatformConfig>();
		if (await (from u in _rep.Context.Queryable<PlatformConfig>()
			where u.WebUrl == input.WebUrl.Trim()
			select u).FirstAsync() != null)
		{
			throw Oops.Bah("当前域名已经OEM，不可重复配置");
		}
		if (!string.IsNullOrEmpty(input.WebUrl) && !string.IsNullOrEmpty(input.SslPwd) && !string.IsNullOrEmpty(input.SslUrl))
		{
			using HttpClient client = HttpClientFactory.Create();
			HttpResponseMessage response = await client.GetAsync(input.SslUrl);
			if (response.StatusCode != HttpStatusCode.OK)
			{
				throw Oops.Oh("请求异常，请稍后再试");
			}
			UtilCertDic.SetCertDic(x509Certificate2: new X509Certificate2(await response.Content.ReadAsByteArrayAsync(), input.SslPwd), key: input.WebUrl);
		}
		await _rep.InsertAsync(entity);
	}

	[HttpPost("/platform/editPlatformConfig")]
	public async Task EditPlatformConfig(PlatformInput input)
	{
		PlatformConfig entity = input.Adapt<PlatformConfig>();
		if (await (from u in _rep.Context.Queryable<PlatformConfig>()
			where (long?)u.Id != input.Id && u.WebUrl == input.WebUrl.Trim()
			select u).FirstAsync() != null)
		{
			throw Oops.Bah("当前域名已经OEM，不可重复配置");
		}
		if (!string.IsNullOrEmpty(input.WebUrl) && !string.IsNullOrEmpty(input.SslPwd) && !string.IsNullOrEmpty(input.SslUrl))
		{
			using HttpClient client = HttpClientFactory.Create();
			HttpResponseMessage response = await client.GetAsync(input.SslUrl);
			if (response.StatusCode != HttpStatusCode.OK)
			{
				throw Oops.Oh("请求异常，请稍后再试");
			}
			UtilCertDic.SetCertDic(x509Certificate2: new X509Certificate2(await response.Content.ReadAsByteArrayAsync(), input.SslPwd), key: input.WebUrl);
		}
		await _rep.UpdateAsync(entity);
	}

	/// <summary>
	/// 获取oem列表
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/platform/getOEMLists")]
	public async Task<dynamic> GetOEMLists([FromQuery] OEMInput input)
	{
		ISugarQueryable<PlatformConfig> query = _rep.Context.Queryable<PlatformConfig>().WhereIF(!string.IsNullOrWhiteSpace(input.WebUrl), (PlatformConfig u) => u.WebUrl.Contains(input.WebUrl.Trim())).WhereIF(!string.IsNullOrWhiteSpace(input.Title), (PlatformConfig u) => u.Title.Contains(input.Title.Trim()));
		query = query.OrderBuilder(input);
		return await query.ToPagedListAsync(input.Page, input.PageSize);
	}

	/// <summary>
	/// 删除OEM配置
	/// </summary>
	/// <param name="id"></param>
	/// <returns></returns>
	[HttpPost("/platform/removeOEM")]
	public async Task RemoveOEM([FromQuery] long id)
	{
		PlatformConfig data = await _rep.GetFirstAsync((PlatformConfig f) => f.Id == id);
		if (data == null)
		{
			throw Oops.Bah("当前OEM配置不存在或已被删除，请刷新后重试");
		}
		await _rep.DeleteAsync(data);
	}
}
